package com.unitd.base.frame.handler;

import com.unitd.base.frame.exception.SpringException;
import com.unitd.base.frame.exception.UnitdException;
import com.unitd.base.frame.plugin.module.dto.ResponseUtils;
import com.unitd.base.module.comm.exception.ApiRRException;
import com.unitd.base.module.comm.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * 异常信息处理器类,用于处理整个app遇到异常时的通用异常处理器
 *
 * @author Hudan
 * @version 1.0
 * @filename GlobalExceptionHandler.java
 * @copyright www.unitd.com
 * @date 2020-05-30
 */
@RestControllerAdvice
@Order(-1)
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常
     */
    @ExceptionHandler(RRException.class)
    public Map<String, Object> handleRRException(RRException e) {
        return ResponseUtils.toResponsObject(e.getCode(), e.getMessage(), null);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Map<String, Object> handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return ResponseUtils.toResponsObject(500, "数据库中已存在该记录", null);
    }

    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseUtils.toResponsObject(500, "系统错误,请稍后重试!", null);
    }


    @ExceptionHandler(ApiRRException.class)
    public Object handleApiRrException(ApiRRException e) {
        return ResponseUtils.toResponsObject(e.getErrno(), e.getErrmsg(), null);
    }

    @ExceptionHandler(UnitdException.class)
    public Object handlUnitdException(UnitdException e) {
        return ResponseUtils.toResponsObject(Integer.parseInt(e.getCode()), e.getMessage(), null);
    }

    @ExceptionHandler(SpringException.class)
    public Object handlUnitdException(SpringException e) {
        return ResponseUtils.toResponsObject(Integer.parseInt(e.getCode()), e.getMessage(), null);
    }
}